package com.jwthhealth_pub.old.sportfitness.view;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jwthhealth_pub.R;
import com.jwthhealth_pub.common.FontManager;
import com.jwthhealth_pub.common.view.TitleLayout;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.common.ImageLoader;
import com.jwthhealth_pub.old.common.download.DownloadManager;
import com.jwthhealth_pub.old.individual.module.SportMyPlanModule;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.old.signutil.model.db.UserInfoDao;
import com.jwthhealth_pub.old.sportfitness.module.SprotCourseInfoModule;
import com.jwthhealth_pub.old.sportfitness.module.SprotCourseModule;
import com.jwthhealth_pub.old.sportfitness.presenter.ISportCourseInfoPresenter;
import com.jwthhealth_pub.old.sportfitness.presenter.ISportCourseInfoPresenterCompl;
import com.jwthhealth_pub.old.sportfitness.view.adapter.SprotCourseInfoAdapter;
import com.jwthhealth_pub.utils.FileUtil;
import com.jwthhealth_pub.utils.NetUtil;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 课程详情
 * Created by Administrator on 2017/1/5.
 */
public class SportCourseInfoActivity extends Activity {

    private static final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/jwth/";
    public static final int downLoading = 0;
    public static final int donwLoadFinish = 1;
    public static final int donwLoadError = 2;

    @BindView(R.id.rb)
    RecyclerView rv;
    @BindView(R.id.join_btn)
    Button joinBtn;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.diffcult)
    TextView diffcult;
    @BindView(R.id.starts)
    TextView starts;
    @BindView(R.id.summary_one)
    TextView summaryOne;
    @BindView(R.id.train_part)
    TextView trainPart;
    @BindView(R.id.train_time)
    TextView trainTime;
    @BindView(R.id.train_pay)
    TextView trainPay;
    @BindView(R.id.summary_thi_thi)
    TextView summaryThiThi;
    @BindView(R.id.summary_thi)
    TextView summaryThi;
    @BindView(R.id.summary_layout)
    RelativeLayout summaryLayout;
    @BindView(R.id.head_count)
    TextView headCount;
    @BindView(R.id.body_count)
    TextView bodyCount;
    @BindView(R.id.btn_right)
    RelativeLayout btnRight;
    @BindView(R.id.summary)
    TextView summary;
    @BindView(R.id.train_summary)
    RelativeLayout trainSummary;
    @BindView(R.id.couser_layout_title)
    TextView couserLayoutTitle;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.cover_layout)
    RelativeLayout coverLayout;
    @BindView(R.id.btn_yes)
    TextView btnYes;
    @BindView(R.id.btn_no)
    TextView btnNo;
    @BindView(R.id.alert_layout)
    RelativeLayout alertLayout;
    @BindView(R.id.green)
    View view;
    @BindView(R.id.download_progressbar)
    ProgressBar downloadProgressbar;
    @BindView(R.id.download_layout)
    RelativeLayout downloadLayout;
    @BindView(R.id.download_percent)
    TextView downloadPercent;
    @BindView(R.id.error_text)
    TextView errorText;
    @BindView(R.id.error_btn)
    Button errorBtn;
    @BindView(R.id.sign_topbar)
    TitleLayout signTopbar;

    private SprotCourseModule.DataBean data;
    private SprotCourseInfoModule body;

    private boolean isRequest;
    private SprotCourseInfoModule.DataBean jumpData;
    private DownLoadReceiver downLoadReceiver;

    public void setRequest(boolean request) {
        isRequest = request;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_course_info);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }

        if (Build.VERSION.SDK_INT >= 23 && (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED))) {
            //andorid 6.0权限问题
            String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
            requestPermissions(permissions, 0);
        }

        data = (SprotCourseModule.DataBean) getIntent().getSerializableExtra(Constant.SPORT_DATA);

        ISportCourseInfoPresenter iSportCourseInfoPresenter = new ISportCourseInfoPresenterCompl(this);

        if (!isRequest) {
            progressbar();
            iSportCourseInfoPresenter.getData(data.getId());
        }

        initTop();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.DOWNLOAD);
        downLoadReceiver = new DownLoadReceiver();
        registerReceiver(downLoadReceiver, intentFilter);
    }

    private void initTop() {
        signTopbar.setTitle("运动健身 " + data.getName());
        signTopbar.setOnTitleLayoutListener(new TitleLayout.TitleLayoutListener() {
            @Override
            public void leftclick() {
                finish();
            }

            @Override
            public void leftTextClick() {

            }

            @Override
            public void rightclick() {

            }

            @Override
            public void rightTextClick() {

            }
        });
    }

    private void renderingUI(final SprotCourseInfoModule.DataBean data) {
//        Picasso.with(this).load(data.getVideo_thumb()).into(img);
        ImageLoader.picasso(data.getVideo_thumb(), img);
        title.setText(data.getName());

        boolean exist = FileUtil.isExist(path + "zip" + data.getId());
        if (exist) {
            joinBtn.setText(getResources().getString(R.string.sport_start_train));
        } else {
            joinBtn.setClickable(false);
            progressbar.setVisibility(View.VISIBLE);
            LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
            if (userinfoModel != null) {
                Call<SportMyPlanModule> sportMyPlanModuleCall = ApiHelper.mySportPlan(userinfoModel.getId(), userinfoModel.getAndroidtoken());
                sportMyPlanModuleCall.enqueue(new Callback<SportMyPlanModule>() {

                    private boolean isJoin;

                    @Override
                    public void onResponse(Call<SportMyPlanModule> call, Response<SportMyPlanModule> response) {
                        joinBtn.setClickable(true);
                        SportMyPlanModule body = response.body();
                        SportCourseInfoActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressbar.setVisibility(View.GONE);
                            }
                        });
                        if (body.getCode().equals("0")) {
                            List<SportMyPlanModule.DataBean.ListBean> list = body.getData().getList();
                            for (int i=0; i<list.size(); i++) {
                                SportMyPlanModule.DataBean.ListBean listBean = list.get(i);
                                String cid = listBean.getCid();
                                String id = data.getId();
                                Log.d("SportCourseInfoActivity", "id" + id);
                                Log.d("SportCourseInfoActivity", "cid" + cid);
                                if (cid.equals(id)) {
                                    joinBtn.setClickable(true);
                                    joinBtn.setText(getResources().getString(R.string.sport_start_train));
                                    isJoin = true;
                                    return;
                                } else {
                                    joinBtn.setClickable(true);
                                    joinBtn.setText(getResources().getString(R.string.sport_train_jion));
                                    isJoin = false;
                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<SportMyPlanModule> call, Throwable t) {
                        SportCourseInfoActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressbar.setVisibility(View.GONE);
                            }
                        });
                    }
                });
            }

        }

        switch (data.getLevel()) {
            case "1":
                starts.setText(getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start_o) +
                        " " + getResources().getString(R.string.icon_sport_start_o) +
                        " " + getResources().getString(R.string.icon_sport_start_o));
                break;
            case "2":
                starts.setText(getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start_o) +
                        " " + getResources().getString(R.string.icon_sport_start_o));
                break;
            case "3":
                starts.setText(getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start_o));
                break;
            case "4":
                starts.setText(getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start) +
                        " " + getResources().getString(R.string.icon_sport_start));
                break;
            default:
                break;
        }

        View[] views = new View[]{starts};
        FontManager.markAsIconContainer(views);

        headCount.setText(data.getHits() + getResources().getString(R.string.sport_count));
        trainPart.setText(data.getSport_body());
        trainPay.setText(data.getTime_long());
        summaryThiThi.setText(data.getSport_result() + getResources().getString(R.string.sport_train_result));
        summary.setText(data.getShort_desc());
        couserLayoutTitle.setText(data.getName());
        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv.setLayoutManager(layout);
        rv.setAdapter(new SprotCourseInfoAdapter(this, data));
    }

    public void progressbar() {
        if (progressbar.getVisibility() == View.VISIBLE) {
            progressbar.setVisibility(View.GONE);
        } else {
            progressbar.setVisibility(View.VISIBLE);
        }

    }

    public Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressbar();
            isRequest = false;
            body = (SprotCourseInfoModule) msg.getData().getSerializable(Constant.SPORT_DATA);
            jumpData = body.getData();
            renderingUI(jumpData);
        }
    };

    @OnClick({R.id.btn_right, R.id.join_btn, R.id.btn_yes, R.id.btn_no,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_right:
                if (body != null) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(Constant.SPORT_DATA, jumpData);
                    Intent intent = new Intent(SportCourseInfoActivity.this, SprotCourseInfoSummaryAcitivty.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    Toast.makeText(this, "数据加载中,请稍后", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.join_btn:

                //判断文件是否存在
                try {
                    boolean exist = FileUtil.isExist(path + "zip" + jumpData.getId());

                    if (!exist) {
                        //判断是否是wifi状态
                        int apnType = NetUtil.getAPNType(SportCourseInfoActivity.this);
                        if (apnType != 1) {
//                        alertLayout.setVisibility(ViewHolder.VISIBLE);
                            showWifiAlert();
                        } else {
                            LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
                            if (userinfoModel == null) {
                                Toast.makeText(this, "登陆状态异常", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            // TODO: 2017/10/27 判断是否有下载文件
                            String url = ApiHelper.sportCourseDownLoadRequest(userinfoModel.getId(), body.getData().getId(), userinfoModel.getAndroidtoken());
                            Log.d("SportCourseInfoActivity", url);

                            File dir = new File(path);
                            if (!dir.exists()) {
                                dir.mkdir();
                            }
                            File file = new File(dir, "jwth");

                            DownloadManager downloadUtil = new DownloadManager(this);
                            downloadUtil.downloadFile(url, path, "zip" + body.getData().getId());

                            joinBtn.setVisibility(View.GONE);
                            downloadLayout.setVisibility(View.VISIBLE);
//                        coverLayout.setVisibility(ViewHolder.VISIBLE);
                        }

                    } else {
                        Intent trainIntent = new Intent(SportCourseInfoActivity.this, SportCourseTrainActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constant.SPORT_DATA, jumpData);
                        trainIntent.putExtras(bundle);
                        startActivity(trainIntent);
                    }
                } catch (Exception e) {
                    Log.d("SportCourseInfoActivity", e.toString());

                }


                break;
            case R.id.btn_yes:
                if (body != null) {
                    LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
                    String url = ApiHelper.sportCourseDownLoadRequest(userinfoModel.getId(), body.getData().getId(), userinfoModel.getAndroidtoken());
                    Log.d("SportCourseInfoActivity", url);

                    File dir = new File(path);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    File file = new File(dir, "jwth");

                    DownloadManager downloadUtil = new DownloadManager(this);
                    downloadUtil.downloadFile(url, path, "zip" + body.getData().getId());

                    joinBtn.setVisibility(View.GONE);
                    downloadLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.btn_no:
                coverLayout.setVisibility(View.GONE);
                alertLayout.setVisibility(View.GONE);
                break;
        }
    }

    private void showWifiAlert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("");
        builder.setMessage(getResources().getString(R.string.sport_alert_wifi));
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (body != null) {
                    LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
                    String url = ApiHelper.sportCourseDownLoadRequest(userinfoModel.getId(), body.getData().getId(), userinfoModel.getAndroidtoken());
                    Log.d("SportCourseInfoActivity", url);

                    File dir = new File(path);
                    if (!dir.exists()) {
                        dir.mkdir();
                    }
                    File file = new File(dir, "jwth");

                    DownloadManager downloadUtil = new DownloadManager(SportCourseInfoActivity.this);
                    downloadUtil.downloadFile(url, path, "zip" + body.getData().getId());

                    joinBtn.setVisibility(View.GONE);
                    downloadLayout.setVisibility(View.VISIBLE);
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                // Permission Denied
                Toast.makeText(this, "拒绝权限程序将无法执行", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @OnClick(R.id.error_btn)
    public void onClick() {
        errorBtn.setVisibility(View.GONE);


        //判断文件是否存在
        boolean exist = FileUtil.isExist(path + "zip" + jumpData.getId());
        if (!exist) {
            //判断是否是wifi状态
            int apnType = NetUtil.getAPNType(SportCourseInfoActivity.this);
            if (apnType != 1) {
//                        alertLayout.setVisibility(ViewHolder.VISIBLE);
                showWifiAlert();
            } else {
                LoginModel.DataBean userinfoModel = UserInfoDao.getInstance().queryUserinfoModel();
                String url = ApiHelper.sportCourseDownLoadRequest(userinfoModel.getId(), body.getData().getId(), userinfoModel.getAndroidtoken());
                Log.d("SportCourseInfoActivity", url);

                File dir = new File(path);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(dir, "jwth");

                DownloadManager downloadUtil = new DownloadManager(this);
                downloadUtil.downloadFile(url, path, "zip" + body.getData().getId());

                joinBtn.setVisibility(View.GONE);
                downloadLayout.setVisibility(View.VISIBLE);
//                        coverLayout.setVisibility(ViewHolder.VISIBLE);
            }

        } else {
            Intent trainIntent = new Intent(SportCourseInfoActivity.this, SportCourseTrainActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.SPORT_DATA, jumpData);
            trainIntent.putExtras(bundle);
            startActivity(trainIntent);
        }
    }

//    private Handler mHander = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            switch (msg.what) {
//                case 0:
//                    break;
//                case 1:
//                    break;
//                case 2:
//                    break;
//                default:
//                    break;
//            }
//        }
//    };


    class DownLoadReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int type = intent.getIntExtra(Constant.BROADCAST_DOWNLOAD_TYPE, 2);
            switch (type) {
                case 0:
                    String percent = intent.getStringExtra(Constant.BROADCAST_DOWNLOAD_PERCENT);
                    int longperCent = intent.getIntExtra(Constant.BROADCAST_DOWNLOAD_LONG_PERCENT, 0);
                    downloadProgressbar.setProgress(longperCent);
                    downloadPercent.setText(getResources().getString(R.string.sport_download_info) + percent);
                    break;
                case 1:
                    joinBtn.setVisibility(View.VISIBLE);
                    joinBtn.setText(getString(R.string.sport_start_train));
                    downloadLayout.setVisibility(View.GONE);
//                    Intent trainIntent = new Intent(SportCourseInfoActivity.this, SportCourseTrainActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable(Constant.SPORT_DATA, jumpData);
//                    trainIntent.putExtras(bundle);
//                    startActivity(trainIntent);
                    break;
                case 2:
                    Toast.makeText(SportCourseInfoActivity.this, "网络错误，请重新下载", Toast.LENGTH_SHORT).show();
                    joinBtn.setVisibility(View.GONE);
                    downloadLayout.setVisibility(View.VISIBLE);
                    errorBtn.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(downLoadReceiver);
    }
}
